class ChatManager {
    constructor() {
        this.socket = new SockJS('/ws');
        this.stompClient = Stomp.over(this.socket);
        this.speechSynthesis = window.speechSynthesis;
        this.connect();
    }

    connect() {
        this.stompClient.connect({}, (frame) => {
            console.log('Connected: ' + frame);
            
            this.stompClient.subscribe('/topic/speech', (response) => {
                this.handleResponse(JSON.parse(response.body));
            });
        }, (error) => {
            console.error('Connection error:', error);
            setTimeout(() => this.connect(), 5000);
        });
    }

    sendMessage(message) {
        const messageElement = this.createMessageElement('user', message);
        document.getElementById('messages').appendChild(messageElement);

        fetch('/api/chat/message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ message: message })
        })
        .then(async response => {
            const data = await response.json();
            if (!response.ok) {
                throw new Error(data.message || `HTTP error! status: ${response.status}`);
            }
            return data;
        })
        .then(data => {
            console.log('Response:', data);
            const responseElement = this.createMessageElement('bot', data.message);
            document.getElementById('messages').appendChild(responseElement);
            
            // 如果没有静音，播放语音
            if (!document.getElementById('mute-button').classList.contains('active')) {
                this.speakResponse(data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            const errorMessage = error.message.includes('Failed to fetch') 
                ? '网络连接错误，请检查网络和代理设置'
                : error.message;
            
            const errorElement = this.createMessageElement('error', errorMessage);
            document.getElementById('messages').appendChild(errorElement);
        });
    }

    createMessageElement(type, message) {
        const div = document.createElement('div');
        div.className = `message ${type}-message`;
        div.textContent = message;
        return div;
    }

    startSpeechRecognition() {
        if ('webkitSpeechRecognition' in window) {
            const recognition = new webkitSpeechRecognition();
            recognition.continuous = false;
            recognition.interimResults = false;
            recognition.lang = 'zh-CN';

            recognition.onresult = (event) => {
                const message = event.results[0][0].transcript;
                this.sendMessage(message);
            };

            recognition.onstart = () => {
                console.log('开始语音识别');
                document.getElementById('voice-button').textContent = '正在听...';
            };

            recognition.onend = () => {
                console.log('语音识别结束');
                document.getElementById('voice-button').textContent = '语音输入';
            };

            recognition.onerror = (event) => {
                console.error('语音识别错误:', event.error);
                const errorElement = this.createMessageElement('error', 
                    '语音识别失败，请重试或使用文字输入');
                document.getElementById('messages').appendChild(errorElement);
            };

            recognition.start();
        } else {
            alert('您的浏览器不支持语音识别功能');
        }
    }

    speakResponse(text) {
        this.speechSynthesis.cancel();

        const utterance = new SpeechSynthesisUtterance(text);
        
        utterance.lang = 'zh-CN';
        utterance.rate = 1.0;
        utterance.pitch = 1.0;
        utterance.volume = 1.0;

        utterance.onstart = () => {
            console.log('开始语音播放');
        };

        utterance.onend = () => {
            console.log('语音播放结束');
        };

        utterance.onerror = (event) => {
            console.error('语音合成错误:', event);
        };

        this.speechSynthesis.speak(utterance);
    }
}

export default ChatManager; 